/**
 * Layout分发容器
 */
import React, { useEffect } from 'react';
import { useLocation, history } from 'umi';
import routes from '@/config/routes';
import { MainLayout, VisualLayout } from './Layout';
import { treeLoopMap } from '@/utils/tree-utils';
import { ErrorBoundary } from '@/widget';
import { judgePermission } from '@/utils';
import routesPermission from '@/config/routes.permission';

// 布局配置
const LAYOUT_CONFIG = {
  mainLayout: MainLayout,
  visualLayout: VisualLayout,
};

// 提取所有路由内的layout
const layoutMap = {};
treeLoopMap(routes, (item) => {
  if (item.layout) layoutMap[item.path] = item.layout;
});

/**
 * 根据当前路由获取对应layout
 * @param {String} pathname 当前路由
 */
const getLayoutComponent = (pathname) => {
  const path = Object.keys(layoutMap).find((item) => pathname.includes(item));
  if (!path) return MainLayout;
  const layoutName = layoutMap[path];
  return LAYOUT_CONFIG[layoutName];
};

const EXCEPTION_PAGE_PATH = ['/403', '/404'];

const App = (props) => {
  const { children } = props;
  const { pathname } = useLocation();
  const Layout = getLayoutComponent(pathname);

  useEffect(() => {
    console.log('=========');
    console.log(pathname);
    if (!EXCEPTION_PAGE_PATH.includes(pathname)) {
      const findRoute = routes.find(({ path }) => pathname === path);
      if (findRoute) {
        const { key } = routesPermission[pathname];
        const hasPermission = judgePermission(key);
        !hasPermission && history.push('/403');
      } else {
        history.push('/404');
      }
    }
  }, [pathname]);

  return (
    <div>
      <ErrorBoundary>
        <Layout>{children}</Layout>
      </ErrorBoundary>
    </div>
  );
};

export default App;
